<template>
  <div class="quest-container">
    <div class="flex mb-16">
      <el-button type="primary" @click="addHandle">添加</el-button>
    </div>
    <el-form :model="searchForm" inline>
      <el-form-item label="任务类型">
        <el-select
          v-model="searchForm.type"
          placeholder="搜索任务类型"
          class="w200px"
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关键字">
        <el-input
          v-model="searchForm.key_word"
          placeholder="输入关键字"
          class="w200px"
        ></el-input>
      </el-form-item>
      <el-space>
        <el-button type="primary" @click="searchHandle">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-space>
    </el-form>
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="location_name" label="任务点位名称" width="200" />
      <el-table-column prop="mission_name" label="任务内容" />
      <el-table-column
        prop="mission_tips"
        label="任务提示"
        width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column prop="points" label="奖励积分" width="150" />
      <el-table-column prop="done_qr_code" label="完成二维码" width="100">
        <template #default="scope">
          <el-image
            style="width: 32px; height: 32px"
            :src="scope.row.done_qr_code"
            @click="codeShowHandle(scope.row.done_qr_code)"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="editHandle(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="1 !== scope.row.type"
            link
            type="danger"
            size="small"
            @click="delHandle(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-24">
      <Pagination
        class="text-center"
        :page="pageForm.page"
        :limit="pageForm.limit"
        :total="tableTotal"
        @pagination="pageHandle"
      />
    </div>
    <!-- 添加/编辑弹窗 -->
    <el-dialog v-model="show" title="添加/编辑任务" width="700">
      <div class="mt-12">
        <el-form
          :model="form"
          ref="formRef"
          label-width="auto"
          style="max-width: 600px"
        >
          <el-form-item label="任务类型">
            <el-radio-group
              v-model="form.type"
              placeholder="请选择任务类型"
              :disabled="editId != ''"
            >
              <el-radio-button
                v-for="item in typeOptions"
                :disabled="1 === item.value"
                :key="item.value"
                :value="item.value"
                >{{ item.label }}</el-radio-button
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="任务内容"
            prop="mission_name"
            :rules="[
              {
                required: true,
                message: '请输入任务内容',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="form.mission_name"
              placeholder="请输入任务内容"
            />
          </el-form-item>
          <el-form-item
            label="任务提示"
            prop="mission_tips"
            :rules="[
              {
                required: true,
                message: '请输入任务提示',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="form.mission_tips"
              placeholder="请输入任务提示"
            />
          </el-form-item>
          <el-form-item label="站点" prop="location_id">
            <el-select
              v-model="form.location_id"
              placeholder="请选择站点"
              class="w100"
            >
              <el-option
                v-for="item in siteOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="奖励积分值" prop="points">
            <el-input v-model="form.points" placeholder="请输入奖励积分值" />
          </el-form-item>
          <el-form-item
            v-if="1 == form.type"
            label="任务图鉴"
            prop="mission_img"
            :rules="[
              {
                required: true,
                message: '请上传任务图鉴',
                trigger: 'blur'
              }
            ]"
          >
            <SingleImage v-model="form.mission_img" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="show = false">取消</el-button>
          <el-button type="primary" @click="formSubmit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 二维码弹窗 -->
    <el-dialog v-model="codeShow" title="二维码" width="360">
      <div class="mt-12">
        <img :src="codeImg" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="downFileHandle"> 下载 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import Pagination from '@/components/Pagination';
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { apiLocationAll } from '@/api/site';
import { downloadURL } from '@/utils/utils';
import SingleImage from '@/components/Upload/SingleImage';
import {
  apiMissionList,
  apiMissionDel,
  apiMissionAdd,
  apiMissionEdit
} from '@/api/mission';
const typeOptions = [
  { label: '主线任务', value: 1 },
  { label: '普通任务', value: 2 }
];
const siteOptions = ref([]);
const getSiteOptions = async () => {
  const { data } = await apiLocationAll();
  siteOptions.value = data;
};
onMounted(() => {
  getSiteOptions();
});
const tableData = ref([]);
const tableTotal = ref(0);
const show = ref(false);
const initalValues = {
  type: 2, // 任务类型，1=主线任务，2=普通任务
  mission_name: '请去XX点位获取一个XX东西', // 任务内容
  mission_tips: 'XX点位在大雁塔的一楼，找旁边工作任务获取', // 任务提示
  location_id: 1, // 点位ID，只有普通任务需要绑定点位，玩一玩看一看不需要
  points: 1, // 奖励积分值
  mission_img: '' // 主线任务才有图鉴
};
const form = ref(initalValues);
const formRef = ref(null);
// 删除
const delHandle = ({ id }) => {
  ElMessageBox.confirm('您确定要删除这个任务吗?', '删除提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      apiMissionDel({
        ids: [id]
      }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          });
          getData();
        }
      });
    })
    .catch(() => {});
};
/**
 * 编辑
 */
const editId = ref('');
const editHandle = (record) => {
  show.value = true;
  formRef.value?.resetFields();
  editId.value = record.id;
  form.value = JSON.parse(JSON.stringify(record));
};
// 添加
const addHandle = () => {
  show.value = true;
  formRef.value?.resetFields();
  editId.value = '';
  form.value = initalValues;
};
/**
 * 表单保存
 */
const formSubmit = async () => {
  await formRef.value.validate(async (valid) => {
    if (valid) {
      const api = editId.value ? apiMissionEdit : apiMissionAdd;
      const params = editId.value
        ? { ...form.value, id: editId.value }
        : form.value;
      const { code } = await api(params);
      if (code === 200) {
        ElMessage({
          type: 'success',
          message: '保存成功'
        });
        show.value = false;
        getData();
      }
    }
  });
};
/**
 * 表格勾选复选框
 */
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  console.log(val);
};
/**
 * 分页
 */
const pageForm = ref({
  page: 1,
  limit: 10
});
const pageHandle = (val) => {
  pageForm.value = val;
  getData();
};
// 搜索
const searchForm = ref({
  key_word: '',
  type: ''
});
const resetSearch = () => {
  searchForm.value = {
    key_word: '',
    type: ''
  };
  searchHandle();
};
const searchHandle = () => {
  pageForm.value.page = 1;
  getData();
};
// 获取表格数据
const getData = async () => {
  const { data, total } = await apiMissionList({
    ...pageForm.value,
    ...searchForm.value
  });
  tableData.value = data;
  tableTotal.value = total;
};
onMounted(() => {
  getData();
});

/**
 * 站点二维码
 */
const codeShow = ref(false);
const codeShowHandle = async (img) => {
  codeShow.value = true;
  codeImg.value = img;
};
const codeImg = ref('');
const downFileHandle = () => {
  const arr = codeImg.value.split('/');
  const filename = arr[arr.length - 1];
  downloadURL(codeImg.value, filename);
};
</script>

<style scoped>
.quest-container {
  position: relative;
  width: 100%;
  height: calc(100vh - 84px);
  padding: 16px;
  box-sizing: border-box;
}
.w200px {
  width: 200px;
}
</style>
